'use client';

import { useRef } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, ModalForm, ProFormText, ProFormTextArea, ProFormSwitch, ProFormItem } from '@ant-design/pro-components';
import { getAgentPage, createAgent, updateAgent, deleteAgent } from '@/apis/admin/agent';
import { Agent } from '@prisma/client';
import FormBuilder from './components/FormBuilder';

const AgentPage = () => {
  const actionRef = useRef<ActionType>(null);

  const columns: ProColumns<Agent>[] = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 260, search: false },
    { title: '智能体名称', dataIndex: 'name', key: 'name' },
    { title: '智能体 Secret Key', dataIndex: 'secretKey', key: 'secretKey', search: false },
    {
      title: '开启表单',
      dataIndex: 'isFormEnabled',
      key: 'isFormEnabled',
      render: (_, record) => (record.isFormEnabled === 1 ? '是' : '否'),
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_, record) => [
        <ModalForm<Agent>
          key="edit"
          title="编辑智能体"
          trigger={<a>编辑</a>}
          onFinish={async (values) => {
            const formJson = values.formJson ? JSON.stringify(values.formJson) : null;
            await updateAgent({ ...record, ...values, formJson ,
              isFormEnabled: values.isFormEnabled ? 1 : 0,  
              canUploadDoc: values.canUploadDoc ? 1 : 0,
              canUploadImg: values.canUploadImg ? 1 : 0,
            });
            message.success('更新成功');
            actionRef.current?.reload();
            return true;
          }}
          initialValues={{...record, formJson: record.formJson ? JSON.parse(record.formJson as string) : { fields: [] }}}
        >
          <ProFormText name="name" label="智能体名称" rules={[{ required: true }]} />
          <ProFormText name="secretKey" label="智能体 Secret Key" rules={[{ required: true }]} />
          <ProFormTextArea name="welcomeText" label="欢迎语" />
          <ProFormSwitch name="canUploadImg" label="允许上传图片" />
          <ProFormSwitch name="canUploadDoc" label="允许上传文档"  />
          <ProFormSwitch name="isFormEnabled" label="开启表单" />
          <ProFormItem name="formJson" label="表单 JSON">
            <FormBuilder />
          </ProFormItem>
        </ModalForm>,
        <Popconfirm
          key="delete"
          title="确定删除吗？"
          onConfirm={async () => {
            await deleteAgent(record.id);
            message.success('删除成功');
            actionRef.current?.reload();
          }}
        >
          <Button type='text' danger>删除</Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<Agent>
      columns={columns}
      actionRef={actionRef}
      request={async (params) => {
        const res = await getAgentPage({ current: params.current || 1, pageSize: params.pageSize || 10, name: params.name });
        return {
          data: res.data,
          success: true,
          total: res.total,
        };
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        defaultCurrent: 1,
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条`,
      }}
      toolBarRender={() => [
          <ModalForm<Omit<Agent, 'id' | 'createdAt' | 'updatedAt'>>
            key="create"
            title="新建智能体"
            trigger={<Button type="primary"><PlusOutlined />新建</Button>}
            onFinish={async (values) => {
              const formJson = values.formJson ? JSON.stringify(values.formJson) : null;
              await createAgent({ ...values, formJson } as any);
              message.success('创建成功');
              actionRef.current?.reload();
              return true;
            }}
          >
            <ProFormText name="name" label="智能体名称" rules={[{ required: true }]} />
            <ProFormText name="secretKey" label="智能体 Secret Key" rules={[{ required: true }]} />
            <ProFormTextArea name="welcomeText" label="欢迎语" />
            <ProFormSwitch name="canUploadImg" label="允许上传图片" />
            <ProFormSwitch name="canUploadDoc" label="允许上传文档" />
            <ProFormSwitch name="isFormEnabled" label="开启表单" />
            <ProFormItem name="formJson" label="表单 JSON">
              <FormBuilder />
            </ProFormItem>
          </ModalForm>,
        ]}
      />
  );
};

export default AgentPage;